package com.xiaojian.pick.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaojian.pick.entity.UserAddress;
import com.xiaojian.pick.page.AjaxResult;
import com.xiaojian.pick.service.UserAddressService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author whycode
 * @title: UserAddressController
 * @projectName campus-secondary-market-app---sys
 * @description: TODO
 * @date 2022/2/208:09
 */
@RestController
@RequestMapping("/address")
public class UserAddressController {

    @Resource
    private UserAddressService userAddressService;

    @PostMapping("/addOrUpdate")
    public AjaxResult addOrUpdate(@RequestBody UserAddress userAddress){
        boolean res = userAddressService.saveOrUpdate(userAddress);
        return new AjaxResult(res);
    }

    @GetMapping("/list/{userId}")
    public AjaxResult list(@PathVariable("userId") Integer userId){

        List<UserAddress> addressList = userAddressService.list(new QueryWrapper<UserAddress>()
                .eq("user_id", userId)
                .eq("status", 0));
        return new AjaxResult(true).setData(addressList);
    }

    @GetMapping("/{id}")
    public AjaxResult getOne(@PathVariable("id") Integer id){
        UserAddress userAddress = userAddressService.getById(id);
        return new AjaxResult(true).setData(userAddress);
    }

    @PutMapping("/update/{id}/{userId}")
    public AjaxResult updateDefault(@PathVariable("id") Integer id,
                                    @PathVariable("userId") Integer userId,
                                    @RequestParam("status") Short status){

        boolean res = userAddressService.updateDefaultById(id, userId, status);

        return new AjaxResult(res);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Integer id){

        boolean res = userAddressService.deleteById(id);

        return new AjaxResult(res);
    }


    @GetMapping("/default/{userId}")
    public AjaxResult queryDefault(@PathVariable("userId") Integer userId){

        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_id", userId)
                .eq("is_default", 1)
                .eq("status", 0);
        List<UserAddress> addresses = userAddressService.list(queryWrapper);
        if(addresses == null || addresses.isEmpty()){
            return new AjaxResult(true);
        }
        return new AjaxResult(true).setData(addresses.get(0));
    }
}
